package cn.emay;

import java.util.HashMap;
import java.util.Map;

import cn.emay.eucp.inter.http.v1.dto.request.BalanceRequest;
import cn.emay.eucp.inter.http.v1.dto.request.MoRequest;
import cn.emay.eucp.inter.http.v1.dto.request.ReportRequest;
import cn.emay.eucp.inter.http.v1.dto.request.SmsBatchOnlyRequest;
import cn.emay.eucp.inter.http.v1.dto.request.SmsSingleRequest;
import cn.emay.eucp.inter.http.v1.dto.response.BalanceResponse;
import cn.emay.eucp.inter.http.v1.dto.response.MoResponse;
import cn.emay.eucp.inter.http.v1.dto.response.ReportResponse;
import cn.emay.eucp.inter.http.v1.dto.response.SmsResponse;
import cn.emay.util.AES;
import cn.emay.util.GZIPUtils;
import cn.emay.util.JsonHelper;
import cn.emay.util.http.EmayHttpClient;
import cn.emay.util.http.EmayHttpRequestBytes;
import cn.emay.util.http.EmayHttpResponseBytes;
import cn.emay.util.http.EmayHttpResponseBytesPraser;
import cn.emay.util.http.EmayHttpResultCode;

public class EmaySMSUtils {

    // 接口地址
    private static String host = "bjmtn.b2m.cn";// 请联系销售获取

    private static String algorithm = "AES/ECB/PKCS5Padding";
    // 编码
    private static String encode = "UTF-8";
    // 是否压缩
    private static Boolean isGzip = false;

    /**
     * 
     * @描述   获取剩余短信条数
     * @作者 jinlizhi
     * @时间 2018年3月20日下午4:56:00
     * @参数 @param appId
     * @参数 @param secretKey
     * @参数 @return
     * @return Long
     */
    public static Long getBalance(String appId, String secretKey) {
        Boolean flag = checkKeyParam(appId, secretKey);
        if (flag) {
            System.out.println("=============begin getBalance==================");
            BalanceRequest pamars = new BalanceRequest();
            ResultModel result = request(appId, secretKey, algorithm, pamars, "http://" + host + "/inter/getBalance",
                    isGzip, encode);
            System.out.println("result code :" + result.getCode());
            if ("SUCCESS".equals(result.getCode())) {
                BalanceResponse response = JsonHelper.fromJson(BalanceResponse.class, result.getResult());
                if (response != null) {
                    System.out.println("result data : " + response.getBalance());
                    System.out.println("=============end getBalance==================");
                    return response.getBalance();
                }
            }
            System.out.println("=============end getBalance==================");
            return null;
        } else {
            System.out.println("=============param check error==================");
            return null;
        }
    }

    /**
     * 
     * @描述 获取报告
     * @作者 jinlizhi
     * @时间 2018年3月20日下午5:17:28
     * @参数 @param appId
     * @参数 @param secretKey
     * @参数 @return
     * @return ReportResponse[]
     */
    public static ReportResponse[] getReport(String appId, String secretKey) {
        Boolean flag = checkKeyParam(appId, secretKey);
        if (flag) {
            System.out.println("=============begin getReport==================");
            ReportRequest pamars = new ReportRequest();
            ResultModel result = request(appId, secretKey, algorithm, pamars, "http://" + host + "/inter/getReport",
                    isGzip, encode);
            System.out.println("result code :" + result.getCode());
            if ("SUCCESS".equals(result.getCode())) {
                ReportResponse[] response = JsonHelper.fromJson(ReportResponse[].class, result.getResult());
                if (response != null) {
                    for (ReportResponse d : response) {
                        System.out.println("result data : " + d.getExtendedCode() + "," + d.getMobile() + ","
                                + d.getCustomSmsId() + "," + d.getSmsId() + "," + d.getState() + "," + d.getDesc() + ","
                                + d.getSubmitTime() + "," + d.getReceiveTime());
                    }
                    System.out.println("=============end getReport==================");
                    return response;
                }
            }
            System.out.println("=============end getReport==================");
            return null;
        } else {
            System.out.println("=============param check error==================");
            return null;
        }
    }

    /**
     * 
     * @描述  发送单条短信
     * @作者 jinlizhi
     * @时间 2018年3月20日下午5:45:38
     * @参数 @param appId
     * @参数 @param secretKey
     * @参数 @param content
     * @参数 @param customSmsId 自定义id
     * @参数 @param extendCode 扩展码用于区分用户回复的短信编码,并且账号支持
     * @参数 @param mobile
     * @参数 @return
     * @return SmsResponse
     */
    public static SmsResponse sendSingleSms(String appId, String secretKey, String content, String customSmsId,
            String extendCode, String mobile) {
        Boolean flag = checkKeyParam(appId, secretKey, mobile);
        if (flag) {
            System.out.println("=============begin setSingleSms==================");
            SmsSingleRequest pamars = new SmsSingleRequest();
            pamars.setContent(content);
            pamars.setCustomSmsId(customSmsId);
            System.out.println("extendCode++++++++++++" + extendCode);
            pamars.setExtendedCode(extendCode);
            pamars.setMobile(mobile);

            ResultModel result = request(appId, secretKey, algorithm, pamars, "http://" + host + "/inter/sendSingleSMS",
                    isGzip, encode);
            System.out.println("result code :" + result.getCode());
            if ("SUCCESS".equals(result.getCode())) {
                SmsResponse response = JsonHelper.fromJson(SmsResponse.class, result.getResult());
                if (response != null) {
                    System.out.println("data : " + response.getMobile() + "," + response.getSmsId() + ","
                            + response.getCustomSmsId());
                }
                System.out.println("=============end setSingleSms==================");
                return response;
            }
            System.out.println("=============end setSingleSms==================");
            return null;
        } else {
            System.out.println("=============param check error==================");
            return null;
        }
    }

    /**
     * 
     * @描述 发送单条短信,无需扩展参数
     * @作者 jinlizhi
     * @时间 2018年3月21日上午9:54:40
     * @参数 @param appId
     * @参数 @param secretKey
     * @参数 @param content
     * @参数 @param mobile
     * @参数 @return
     * @return SmsResponse
     */
    public static SmsResponse sendSingleSms(String appId, String secretKey, String content, String mobile) {
        return sendSingleSms(appId, secretKey, content, null, null, mobile);
    }

    /**
     * 
     * @描述 获取上行(如果支持的话)
     * @作者 jinlizhi
     * @时间 2018年3月21日上午9:49:09
     * @参数 @param appId
     * @参数 @param secretKey
     * @参数 @return
     * @return MoResponse[]
     */
    public static MoResponse[] getMo(String appId, String secretKey) {
        Boolean flag = checkKeyParam(appId, secretKey);
        if (flag) {
            System.out.println("=============begin getMo==================");
            MoRequest pamars = new MoRequest();
            ResultModel result = request(appId, secretKey, algorithm, pamars, "http://" + host + "/inter/getMo", isGzip,
                    encode);
            System.out.println("result code :" + result.getCode());
            if ("SUCCESS".equals(result.getCode())) {
                MoResponse[] response = JsonHelper.fromJson(MoResponse[].class, result.getResult());
                if (response != null) {
                    for (MoResponse d : response) {
                        System.out.println("result data:" + d.getContent() + "," + d.getExtendedCode() + ","
                                + d.getMobile() + "," + d.getMoTime());
                    }
                }
                System.out.println("=============end getMo==================");
                return response;
            }
            System.out.println("=============end getMo==================");
            return null;
        } else {
            System.out.println("=============param check error==================");
            return null;
        }
    }

    /**
     * 
     * @描述 支持扩展码(如果账号支持的话)的批量发送短信
     * @作者 jinlizhi
     * @时间 2018年3月21日上午10:04:16
     * @参数 @param appId
     * @参数 @param secretKey
     * @参数 @param content
     * @参数 @param extendCode
     * @参数 @param mobiles
     * @参数 @return
     * @return SmsResponse[]
     */
    public static SmsResponse[] sendBatchOnlySms(String appId, String secretKey, String content, String extendCode,
            String[] mobiles) {
        Boolean flag = checkKeyParam(appId, secretKey, mobiles);
        if (flag) {

        } else {
            System.out.println("=============param check error==================");
            return null;
        }
        System.out.println("=============begin setBatchOnlySms==================");
        SmsBatchOnlyRequest pamars = new SmsBatchOnlyRequest();
        pamars.setMobiles(mobiles);
        pamars.setExtendedCode(extendCode);
        pamars.setContent(content);
        ResultModel result = request(appId, secretKey, algorithm, pamars, "http://" + host + "/inter/sendBatchOnlySMS",
                isGzip, encode);
        System.out.println("result code :" + result.getCode());
        if ("SUCCESS".equals(result.getCode())) {
            SmsResponse[] response = JsonHelper.fromJson(SmsResponse[].class, result.getResult());
            if (response != null) {
                for (SmsResponse d : response) {
                    System.out.println("data:" + d.getMobile() + "," + d.getSmsId() + "," + d.getCustomSmsId());
                }
            }
            System.out.println("=============end setBatchOnlySms==================");
            return response;
        }
        System.out.println("=============end setBatchOnlySms==================");
        return null;
    }

    /**
     * 
     * @描述 群发短信不需要扩展码
     * @作者 jinlizhi
     * @时间 2018年3月21日上午10:35:24
     * @参数 @param appId
     * @参数 @param secretKey
     * @参数 @param content
     * @参数 @param mobiles
     * @参数 @return
     * @return SmsResponse[]
     */
    public static SmsResponse[] sendBatchOnlySms(String appId, String secretKey, String content, String[] mobiles) {
        return sendBatchOnlySms(appId, secretKey, content, null, mobiles);
    }

    /**
     * 
     * @描述 校验key与secret
     * @作者 jinlizhi
     * @时间 2018年3月21日上午10:40:00
     * @参数 @param appId
     * @参数 @param secretKey
     * @参数 @return
     * @return Boolean
     */
    private static Boolean checkKeyParam(String appId, String secretKey) {
        if (null == appId || secretKey == null || appId.trim().equals("") || secretKey.trim().equals("")) {
            return false;
        }
        return true;
    }

    /**
     * 
     * @描述 校验key与secret,mobile
     * @作者 jinlizhi
     * @时间 2018年3月21日上午11:04:08
     * @参数 @param appId
     * @参数 @param secretKey
     * @参数 @param mobile
     * @参数 @return
     * @return Boolean
     */
    private static Boolean checkKeyParam(String appId, String secretKey, String mobile) {
        if (null == appId || secretKey == null || mobile == null || appId.trim().equals("")
                || secretKey.trim().equals("") || mobile.trim().equals("") || mobile.trim().equals("")) {
            return false;
        }
        return true;
    }

    /**
     * 
     * @描述 校验key与secret,mobiles[]
     * @作者 jinlizhi
     * @时间 2018年3月21日上午11:13:57
     * @参数 @param appId
     * @参数 @param secretKey
     * @参数 @param mobiles
     * @参数 @return
     * @return Boolean
     */
    private static Boolean checkKeyParam(String appId, String secretKey, String[] mobiles) {
        if (null == appId || secretKey == null || mobiles == null || appId.trim().equals("")
                || secretKey.trim().equals("") || mobiles.length == 0) {
            return false;
        }
        return true;
    }

    /**
     * 公共请求方法
     */
    private static ResultModel request(String appId, String secretKey, String algorithm, Object content, String url,
            final boolean isGzip, String encode) {
        Map<String, String> headers = new HashMap<String, String>();
        EmayHttpRequestBytes request = null;
        try {
            headers.put("appId", appId);
            headers.put("encode", encode);
            String requestJson = JsonHelper.toJsonString(content);
            System.out.println("result json: " + requestJson);
            byte[] bytes = requestJson.getBytes(encode);
            //System.out.println("request data size : " + bytes.length);
            if (isGzip) {
                headers.put("gzip", "on");
                bytes = GZIPUtils.compress(bytes);
                //System.out.println("request data size [com]: " + bytes.length);
            }
            byte[] parambytes = AES.encrypt(bytes, secretKey.getBytes(), algorithm);
            //System.out.println("request data size [en] : " + parambytes.length);
            request = new EmayHttpRequestBytes(url, encode, "POST", headers, null, parambytes);
        } catch (Exception e) {
            System.out.println("加密异常");
            e.printStackTrace();
        }
        EmayHttpClient client = new EmayHttpClient();
        String code = null;
        String result = null;
        try {
            EmayHttpResponseBytes res = client.service(request, new EmayHttpResponseBytesPraser());
            if (res == null) {
                System.out.println("请求接口异常");
                return new ResultModel(code, result);
            }
            if (res.getResultCode().equals(EmayHttpResultCode.SUCCESS)) {
                if (res.getHttpCode() == 200) {
                    code = res.getHeaders().get("result");
                    if (code.equals("SUCCESS")) {
                        byte[] data = res.getResultBytes();
                        //System.out.println("response data size [en and com] : " + data.length);
                        data = AES.decrypt(data, secretKey.getBytes(), algorithm);
                        if (isGzip) {
                            data = GZIPUtils.decompress(data);
                        }
                        //System.out.println("response data size : " + data.length);
                        result = new String(data, encode);
                        System.out.println("response json: " + result);
                    }
                } else {
                    System.out.println("请求接口异常,请求码:" + res.getHttpCode());
                }
            } else {
                System.out.println("请求接口网络异常:" + res.getResultCode().getCode());
            }
        } catch (Exception e) {
            System.out.println("解析失败");
            e.printStackTrace();
        }
        ResultModel re = new ResultModel(code, result);
        return re;
    }

    /*    public static void main(String[] args) {
    
    Long balance1 = getBalance1(appId, secretKey);
    System.out.println(balance1);
    ReportResponse[] report1 = getReport1(appId, secretKey);
    System.out.println(report1);
    // SmsResponse setSingleSms1 = setSingleSms1(appId, secretKey,
    // "【签名】5你好今天天气不错，挺风和日丽的5","abc","123", "15848839055");
    // System.out.println(setSingleSms1);
    MoResponse[] mo1 = getMo1(appId, secretKey);
    System.out.println(mo1);
    
    }*/

}
